<!--添加包租合同-->
<template>
	<a-modal v-bind="option" class="add-charter">
		<a-form ref="form" :model="entity" layout="vertical" :rules="charterContractRules(entity)">
			<a-typography-paragraph strong>
				<blockquote>企业信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="8">
					<a-form-item label="企业名称：" name="enterPriseId">
						<a-select
							:disabled="props.id !== ''"
							v-model:value="entity.enterPriseId"
							placeholder="请选择企业"
							:options="options.enterpriseList"
							allow-clear
							show-search
							option-filter-prop="name"
							:field-names="{label: 'enterPriseName', value: 'id'}"
							@change="selectEnterPriseId" />
					</a-form-item>
				</a-col>
				<template v-if="entity.enterPriseId">
					<a-col :span="8">
						<a-form-item label="统一社会信用代码：">
							<a-input v-model:value="entity.societyCode" disabled placeholder="请输入社会信用代码" style="flex: 1" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="联系人信息：">
							<a-input disabled :placeholder="entity.linkmanName + '/' + entity.linkmanPhone" style="flex: 1" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="合作周期：" name="enterPriseTeamWorkId">
							<a-select
								:disabled="props.id !== ''"
								v-model:value="entity.enterPriseTeamWorkId"
								placeholder="请选择合作周期"
								:options="options.teamWork"
								:field-names="{label: 'period', value: 'id'}"
								@change="selectWorkId" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="租金协议价：" name="enterPriseTeamworkDiscountId">
							<a-select
								:disabled="props.id !== ''"
								v-model:value="entity.enterPriseTeamworkDiscountId"
								placeholder="请选择租金协议价"
								:options="options.discount"
								:field-names="{label: 'name', value: 'id'}"
								@change="selectDiscountId" />
						</a-form-item>
					</a-col>
				</template>
			</a-row>

			<a-typography-paragraph strong>
				<blockquote>
					房间信息
					<a @click="onClickToSelectHouse">
						<plus-circle-outlined />
					</a>
					<template v-if="entity.enterPriseContractHouseRoomFroms?.length">
						（原有{{ originalTotal }}间,新选{{ newEletedTotal }}间,共{{ originalTotal + newEletedTotal }}间）
					</template>
				</blockquote>
			</a-typography-paragraph>
			<a-form-item v-if="entity.enterPriseContractHouseRoomFroms?.length" name="">
				<a-form-item-rest>
					<vxe-table ref="houseInfoTable" :data="(entity.enterPriseContractHouseRoomFroms as [])" v-bind="houseTableOption">
						<vxe-column field="houseAddress" min-width="300" align="left" title="房源地址"></vxe-column>
						<vxe-column min-width="130px" align="right" title="租金/优惠价(元/月)">
							<template #default="{row}">{{ row.price }}/{{ row.countPprice }}</template>
						</vxe-column>
						<vxe-column field="deposit" min-width="100px" align="right" title="押金(元)">
							<template #default="{row}">{{ row.countDeposit }}</template>
						</vxe-column>
						<vxe-column field="currentFloor" min-width="80px" align="right" title="楼层"></vxe-column>
						<vxe-column field="houseArea" min-width="80px" align="right" title="面积"></vxe-column>
						<vxe-column field="houseRoomTypeName" min-width="80px" align="right" title="房型"></vxe-column>
						<vxe-column title="操作" width="75px" align="center">
							<template #default="{row, rowIndex}">
								<a
									v-if="!row.isShowStatus"
									v-color="{color: 'danger'}"
									@click="onClickToRemoveRow(rowIndex, houseInfoTable as VxeTableInstance)">
									<svg-icon icon-class="trash" />
								</a>
								<p v-else>--</p>
							</template>
						</vxe-column>
					</vxe-table>
				</a-form-item-rest>
				<!--实现表单校验失败滚动到此处-->
				<a-input :bordered="false" style="position: absolute" />
			</a-form-item>
			<a-typography-paragraph v-else style="margin-bottom: 2em" />

			<a-typography-paragraph strong>
				<blockquote>承租人信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="6">
					<a-form-item label="姓名：" :name="['renterInfo', 'name']">
						<a-input-group compact class="display-flex">
							<a-input v-model:value="entity.renterInfo.name" placeholder="请输入姓名" disabled style="flex: 1" />
							<a-form-item-rest>
								<a-radio-group v-model:value="entity.renterInfo.gender" button-style="solid">
									<a-radio-button :value="1">男</a-radio-button>
									<a-radio-button :value="2">女</a-radio-button>
								</a-radio-group>
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="手机号：" :name="['renterInfo', 'phone']">
						<a-input v-model:value.trim="entity.renterInfo.phone" :maxlength="11" disabled placeholder="请输入手机号" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="身份信息：" :name="['renterInfo', 'identityCard']">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									v-model:value="entity.renterInfo.certificationType"
									:options="options.certificateTypes"
									:disabled="entity.contractMedium === 2 || props.id !== ''"
									@change="form?.clearValidate([['renterInfo', 'identityCard'] as unknown as string])"
									style="width: 120px" />
							</a-form-item-rest>
							<a-input
								:disabled="props.id !== ''"
								v-model:value.trim="entity.renterInfo.identityCard"
								:maxlength="18"
								placeholder="请输入证件号码"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="证件照片：">
						<a-button type="primary" block @click=";(visibles.certificate = true), (renter = entity.renterInfo as RenterInfo)">
							<template v-if="entity.renterInfo.frontImgUrl || entity.renterInfo.rearImgUrl">
								<check-outlined />
							</template>
							<plus-outlined v-else />
						</a-button>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="客户来源：">
						<a-select
							:disabled="props.id !== ''"
							v-model:value="entity.renterInfo.customerResource"
							placeholder="请选择客户来源"
							:options="options.sources"
							allow-clear
							show-search
							option-filter-prop="name"
							:field-names="DEFAULT_FIELD_NAME" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="收付款账号：">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									v-model:value="entity.renterInfo.paymentType"
									:options="paymentAccountList"
									placeholder="请选择类型"
									:disabled="props.id !== ''"
									style="width: 100px" />
							</a-form-item-rest>
							<a-input
								:disabled="props.id !== ''"
								v-model:value.trim="entity.renterInfo.paymentNo"
								placeholder="请输入账号"
								:maxlength="30"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="紧急联系人：" :name="['renterInfo', 'emergencyName']">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									:disabled="props.id !== ''"
									v-model:value="entity.renterInfo.emergencyType"
									:options="relationshipList"
									placeholder="关系"
									style="width: 100px" />
							</a-form-item-rest>
							<a-input
								:disabled="props.id !== ''"
								v-model:value="entity.renterInfo.emergencyName"
								placeholder="请输入联系人姓名"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="紧急联系人手机号：" :name="['renterInfo', 'emergencyPhone']">
						<a-input-group compact>
							<a-input
								:disabled="props.id !== ''"
								v-model:value.trim="entity.renterInfo.emergencyPhone"
								:maxlength="11"
								placeholder="请输入联系人手机号" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="职业：">
						<a-select
							:disabled="props.id !== ''"
							v-model:value="entity.renterInfo.profession"
							placeholder="请选择职业"
							:options="occupation"
							allow-clear
							show-search />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="工作单位：">
						<a-input :disabled="props.id !== ''" v-model:value.trim="entity.renterInfo.employer" placeholder="请输入工作单位" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="重点人群：">
						<a-select
							:disabled="props.id !== ''"
							v-model:value="entity.renterInfo.keyGroupsType"
							placeholder="请选择重点人群"
							:options="options.keyGroups"
							allow-clear
							show-search
							option-filter-prop="name"
							:field-names="DEFAULT_FIELD_NAME" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="爱好：">
						<a-tooltip :title="hobbies.join('，') || '请选择爱好'" destroy-tooltip-on-hide>
							<a-select
								:disabled="props.id !== ''"
								v-model:value="entity.renterInfo.interest"
								placeholder="请选择爱好"
								mode="multiple"
								:options="options.hobbies"
								allow-clear
								show-search
								max-tag-count="responsive"
								option-filter-prop="name"
								:field-names="DEFAULT_FIELD_NAME" />
						</a-tooltip>
					</a-form-item>
				</a-col>
			</a-row>

			<a-typography-paragraph strong>
				<blockquote>合同信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="6">
					<a-form-item label="成交方式/合同编号：" name="contractNo">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select v-model:value="entity.signType" disabled :options="signTypeList" style="width: 80px" />
							</a-form-item-rest>
							<a-input
								:disabled="props.id !== ''"
								v-model:value.trim="entity.contractNo"
								placeholder="请输入合同编号"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item name="beginTime">
						<template #label>
							<div class="display-flex" style="justify-content: flex-start">
								<span>合同周期：</span>
								<span v-if="entity.enterPriseTeamWorkId">（企业合作周期：{{ options.teamWork[0].period }}）</span>
								<!-- <span v-if="entity.enterPriseTeamWorkId">（企业合作周期：{{ options.teamWork?.filter((e: any) => e.id === entity.enterPriseTeamWorkId)[0].period }}）</span> -->
							</div>
						</template>
						<a-input-group compact class="display-flex">
							<a-range-picker
								:value="[entity.beginTime, entity.endTime]"
								:value-format="DATE_FORMAT.DATE"
								:disabled-date="disabledDate"
								style="flex: 1"
								@change="onDateChange" />
							<a-form-item-rest>
								<a-radio-group
									class="month-quick-radio-group"
									v-model:value="entity.leasePeriod"
									button-style="solid"
									@change="quickSelectDate">
									<a-radio-button :value="6">半年</a-radio-button>
									<a-radio-button :value="12">1年</a-radio-button>
									<a-radio-button :value="24">2年</a-radio-button>
									<a-radio-button :value="36">3年</a-radio-button>
								</a-radio-group>
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="月租金：" name="price">
						<a-input-number v-model:value="entity.price" :min="0" :precision="2" disabled placeholder="请输入租金" />
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="押金：" name="deposit">
						<a-input-number v-model:value="entity.deposit" :min="0" :precision="2" disabled placeholder="请输入押金" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="付款方式：">
						<a-input-group compact class="display-flex">
							<a-select
								:disabled="props.id !== ''"
								v-model:value="entity.depositMonth"
								:options="mortgageMonthList"
								placeholder="请选择"
								style="flex: 1" />
							<a-select
								:disabled="props.id !== ''"
								v-model:value="entity.periodMonth"
								:options="periodMonthList"
								placeholder="请选择"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="收租日设置：" name="payPatternValue">
						<a-input-group compact class="display-flex">
							<template v-if="entity.payPattern == 1">
								<a-input-number
									:disabled="props.id !== ''"
									v-model:value="entity.payPatternValue"
									prefix="提前"
									:precision="0"
									style="flex: 1; display: flex" />
							</template>
							<template v-else>
								<a-input-number
									:disabled="props.id !== ''"
									v-model:value="entity.payPatternValue"
									prefix="固定"
									:min="1"
									:max="31"
									:precision="0"
									style="flex: 1; display: flex" />
							</template>
							<a-form-item-rest>
								<a-select
									:disabled="props.id !== ''"
									v-model:value="entity.payPattern"
									:options="paymentMethodList"
									style="width: 200px"
									@change="entity.payPatternValue = null" />
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="账单生成规则：">
						<a-select
							:disabled="props.id !== ''"
							v-model:value="entity.cycleType"
							:options="waningMoonList"
							placeholder="请选择账单生成规则" />
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="合同附件：">
						<a-button type="primary" block @click="visibles.attachment = true">
							<check-outlined v-if="entity.attachmentIds?.length" />
							<plus-outlined v-else />
						</a-button>
					</a-form-item>
				</a-col>
				<a-col :span="24">
					<a-form-item label="补充说明：" name="addExplanation">
						<a-textarea
							v-model:value.trim="entity.addExplanation"
							placeholder="请输入补充说明"
							:rows="4"
							show-count
							:maxlength="200" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-typography-paragraph strong>
				<blockquote>
					费用支付配置
					<a @click="onClickToCostConfig">
						<setting-outlined />
					</a>
				</blockquote>
			</a-typography-paragraph>
			<a-typography-paragraph style="margin-bottom: 2em" />

			<a-typography-paragraph strong>
				<blockquote>
					加收费用
					<a @click="onClickToAddOtherBill">
						<plus-circle-outlined />
					</a>
				</blockquote>
			</a-typography-paragraph>
			<a-form-item v-if="entity.otherExpenses?.length" name="otherExpenses">
				<a-form-item-rest>
					<vxe-table ref="otherBillTable" :data="entity.otherExpenses" v-bind="otherBillTableOption">
						<vxe-column min-width="150px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								费用科目
							</template>
							<template #default="{row, rowIndex}">
								<a-select
									v-model:value="row.feeSubjectId"
									:bordered="false"
									:options="options.feeSubjects"
									show-search
									option-filter-prop="name"
									:field-names="{label: 'name', value: 'id', options: 'metaList'}"
									placeholder="请选择费用科目" />
							</template>
						</vxe-column>
						<vxe-column min-width="150px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								付款方式
							</template>
							<template #default="{row, rowIndex}">
								<a-select
									v-model:value="row.periodMonth"
									:bordered="false"
									:options="periodMonthOptions"
									placeholder="请选择付款方式" />
							</template>
						</vxe-column>
						<vxe-column min-width="150px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								金额
							</template>
							<template #default="{row, rowIndex}">
								<a-input-number
									v-model:value="row.price"
									:bordered="false"
									:controls="false"
									:min="0"
									:precision="2"
									placeholder="请输入金额" />
							</template>
						</vxe-column>
						<vxe-column title="操作" width="60px" align="center">
							<template #default="{row, rowIndex}">
								<a v-color="{color: 'danger'}" @click="onClickToRemoveRow(rowIndex, otherBillTable as VxeTableInstance)">
									<svg-icon icon-class="trash" />
								</a>
							</template>
						</vxe-column>
					</vxe-table>
				</a-form-item-rest>
				<!--实现表单校验失败滚动到此处-->
				<a-input :bordered="false" style="position: absolute" />
			</a-form-item>
			<a-typography-paragraph v-else style="margin-bottom: 2em" />

			<a-typography-paragraph strong>
				<blockquote>签约信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="8">
					<a-form-item label="签约人/维护人：" name="signEmpId">
						<dept-emp-select
							:disabled="props.id !== ''"
							v-model:dept-id="entity.signDeptId"
							v-model:emp-id="entity.signEmpId"
							@change="form?.validate('signEmpId')" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="签约时间：" name="signTime">
						<a-date-picker v-model:value="entity.signTime" placeholder="请选择签约日期" :value-format="DATE_FORMAT.DATE" />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<template #footer>
			<a-button type="primary" :disabled="disables.save" :loading="loadings.save" @click="submit">保存并核对账单</a-button>
		</template>

		<!-- 选择房间 -->
		<select-house v-model:visible="visibles.selectHouse" :house-info-id="houseInfoId" @success="onSubmitSuccess" />
		<!-- 附件上传 -->
		<file-upload-dialog v-model:visible="visibles.attachment" v-model:files="attachments" />
		<!-- 证件上传 -->
		<certificate-upload-dialog v-model:visible="visibles.certificate" :imgs="renter" />
		<!-- 费用配置 -->
		<CostConfig v-model:visible="visibles.costConfig" :cost="(entity.costPaymentConfigs as [])" @success="onSubmitCost" />
		<!-- 账单预览 -->
		<enter-bill-preview-dialog v-model:visible="visibles.billPreview" :contract="entity" @success="onSubmitBill" />
	</a-modal>
</template>

<script lang="ts" setup>
	import dayjs, {Dayjs} from 'dayjs'
	import {useStore} from '@/store'
	import XEUtils from 'xe-utils'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {computed, createVNode, reactive, ref, toRaw, toRef, watch, watchEffect} from 'vue'
	import {
		mortgageMonthList,
		occupation,
		paymentAccountList,
		paymentMethodList,
		periodMonthList,
		periodMonthOptions,
		relationshipList,
		renterRelationList,
		signTypeList,
		waningMoonList
	} from '@/utils'
	import {
		CheckOutlined,
		PlusOutlined,
		PlusCircleFilled,
		PlusCircleOutlined,
		QuestionCircleOutlined,
		SettingOutlined
	} from '@ant-design/icons-vue'
	import CertificateUploadDialog from '@/components/common/certificate-upload-dialog.vue'
	import {Img} from 'yuxin-base/src/types'
	import DATE_FORMAT, {nowDate} from 'yuxin-base/src/utils/date'
	import {DEFAULT_FIELD_NAME, DIC_LABEL_MAP, DIC_PID_MAP} from 'yuxin-base/src/constant'
	import {VxeTableInstance, VxeTableProps} from 'vxe-table'
	import {Empty, FormInstance, message, Modal} from 'ant-design-vue'
	import {HouseDetail} from '@/interface/house'
	import {charterContractRules} from '@/rules/contract'
	import FileUploadDialog from '@/components/common/file-upload-dialog.vue'
	import {getRenterContractDetail} from '@/api/contract'
	import EnterBillPreviewDialog from '@/components/contract/add-charter/enter-bill-preview-dialog.vue'
	import {
		defaultRenterContract,
		defaultRenterInfo,
		RenterContract,
		RenterContractDevice,
		RenterInfo,
		CharterContract
	} from '@/interface/contract'
	import {getEnterContractDetails} from '@/api/charter-contract'
	import {CERTIFICATION_TYPE_MAP} from 'yuxin-base/src/constant/index'
	import SelectHouse from '@/components/contract/add-charter/select-house.vue'
	import CostConfig from '@/components/contract/add-charter/cost-config.vue'
	import billApi from '@/api/bill-api'
	import houseApi from '@/api/house-api'
	import {discountTypeOptions} from '@/interface/interface'
	import {enterpriseDetails} from '@/api/enterprise-library'

	const store = useStore()

	const props = withDefaults(
		defineProps<{
			visible?: boolean
			contract?: RenterContract
			// data?: any
			id?: string
			ids?: any
		}>(),
		{
			contract: {
				// @ts-ignore成交方式【1-新签,2-续签,3-转租,4-换房】，默认新签
				signType: 1
			},
			id: '',
			ids: {}
		}
	)

	const loadings = reactive({
		save: false,
		search: false
	})

	const disables = reactive({
		save: false
	})

	const visibles = reactive({
		selectHouse: false,
		attachment: false,
		certificate: false,
		costConfig: false,
		billPreview: false
	})
	const originalTotal = ref<number>(0)
	const newEletedTotal = ref<number>(0)
	const originalList = ref<any>([])

	const emits = defineEmits(['update:visible', 'success'])
	const option = reactive({
		width: 1100,
		title: '补签协议',
		centered: true,
		keyboard: false,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			attachments.value = []
			newEletedTotal.value = 0
			originalTotal.value = 0
			reset()
			emits('update:visible', false)
		}
	})

	// 表单内容
	const form = ref<FormInstance>()
	// 租客信息
	const renter = ref<RenterInfo>({})
	// 合同附件
	const attachments = ref<Img[]>([])
	// 合同信息
	const entity = reactive<CharterContract>(defaultRenterContract())
	// 租客原始信息
	const originRenterInfo = ref<RenterInfo>({})

	// 周期时长提示
	const cycleTip = ref<string>()

	// 续租企业信息禁止编辑
	const isDisabled = computed(() => {
		return false
	})

	// 爱好
	const hobbies = computed(() => {
		const interest = (entity.renterInfo || {}).interest || []
		return options.hobbies.filter((item: any) => interest.includes(item.id)).map((item: any) => item.name)
	})

	const teamWork = ref<any>({})
	/**
	 * 当前折扣比例
	 */
	const discountScale = ref<any>()

	/**
	 * 当前租金折扣类型 1每月折 2首月折 3尾月折
	 */
	const discountType = ref<any>()

	/**
	 * 已选择房间id数组
	 */
	const houseInfoId = ref<any>()

	const enterPrise = reactive<any>({})

	const disabledDate = (current: Dayjs) => {
		// let beginTime = options.teamWork?.filter((e: any) => e.id === entity.enterPriseTeamWorkId)[0]?.beginTime
		// let endTime = options.teamWork?.filter((e: any) => e.id === entity.enterPriseTeamWorkId)[0]?.endTime
		// if (beginTime || endTime) {
		// 	return current.isBefore(beginTime, 'day') || current.isAfter(endTime, 'day')
		// }
		let beginTime = dayjs().format(DATE_FORMAT.DATE)
		let endTime = teamWork.value?.endTime
		if (beginTime || endTime) {
			return current.isBefore(beginTime, 'day') && current.isAfter(beginTime, 'day')
		}
	}

	/**
	 * 计算合同周期月数
	 */
	watchEffect(() => {
		if (entity.beginTime && entity.endTime) {
			const endTime = dayjs(entity.endTime).add(1, 'day')

			let months = endTime.diff(entity.beginTime, 'month', true)

			entity.leasePeriod = XEUtils.toInteger(months)
		}
	})
	// 计算押金
	watch(
		() => entity.depositMonth,
		() => {
			// 重新计算
			entity.deposit = 0
			entity.enterPriseContractHouseRoomFroms?.forEach((e: any) => {
				let price = e.price
				if (discountType.value === 1) {
					price = (e.price * Number(discountScale.value)) / 100
				}

				entity.deposit += price
			})
			entity.deposit = XEUtils.multiply(entity.deposit, entity.depositMonth)
			entity.deposit = Number(entity.deposit.toFixed(2))
		}
	)
	const canceled = ref(true)
	watch(
		() => props.visible,
		(newVal: boolean) => {
			if (newVal) {
				// 续租逻辑
				if (canceled.value && props.contract?.signType === 2) {
					emits('update:visible', false)
					billApi.unclearedDeposit(props.contract?.contractId as string).then(({data = []}) => {
						if (data.length > 0) {
							message.error('原合同押金未结清，不能进行续租操作')
						} else {
							emits('update:visible', true)
							canceled.value = false
						}
					})

					return
				}

				getDisc()
				const contract = props.contract || {}

				let renterInfo = contract.renterInfo || {}

				if (contract.otherExpenses && XEUtils.isString(contract.otherExpenses)) {
					try {
						contract.otherExpenses = JSON.parse(contract.otherExpenses || '[]')
					} catch (e) {
						contract.otherExpenses = []
					}
				}

				// @ts-ignore，过滤掉空值
				renterInfo = XEUtils.pick(renterInfo, v => v)
				originRenterInfo.value = renterInfo

				delete contract.renterInfo

				if (XEUtils.isString(renterInfo.interest) && XEUtils.trim(renterInfo.interest)) {
					renterInfo.interest = renterInfo.interest.split('/')
				}

				XEUtils.merge(entity, defaultRenterContract(), contract, {
					contractId: null,
					contractNo: null,
					signEmpId: store.currentUser.empId,
					signDeptId: store.currentUser.deptId,
					signTime: nowDate(),
					// 包租合同自定义
					enterPriseId: null,
					enterPriseTeamWorkId: null,
					enterPriseTeamworkDiscountId: null,
					societyCode: null,
					linkmanPhone: null,
					enterPriseContractHouseRoomFroms: [],
					leasePeriod: 6,
					endTime: dayjs().add(6, 'month').add(-1, 'day').format(DATE_FORMAT.DATE),
					costPaymentConfigs: []
				})

				// 续租需要传contractId
				if (contract.contractId) {
					getContractDetail(contract.contractId)
				}
			}
		}
	)

	// 获取合同详情
	const getContractDetail = (id: string) => {
		getRenterContractDetail(id).then(({data}: {data: RenterContract}) => {
			const renterInfo = data.renterInfo || {}

			const signType = props.contract?.signType || 1

			if (signType > 1 && !entity.reset && !entity.resubmit) {
				data.contractId = null
				data.contractPid = id
				data.signType = signType
				data.signTime = nowDate()
				data.otherExpenses = []

				switch (signType) {
					case 2:
						// 续签周期计算
						data.beginTime = dayjs(data.endTime).add(1, 'day').format(DATE_FORMAT.DATE)
						if (props.contract?.endTime && props.contract.applyId) {
							data.endTime = props.contract.endTime
						} else {
							data.endTime = dayjs(data.beginTime).add(1, 'year').subtract(1, 'day').format(DATE_FORMAT.DATE)
						}
						break
				}
			}

			// @ts-ignore
			data = XEUtils.pick(data, v => v)
			// @ts-ignore
			data.renterInfo = XEUtils.pick(renterInfo, v => v)

			XEUtils.merge(entity, data)

			delete entity.house

			console.log('合同详情==============>', toRaw(data))

			// 房间信息需要重新处理
			getHouseRoom(entity.houseId as string)
		})
	}

	// 当前签约房源
	const getHouseRoom = (id: string) => {
		entity.houseId = id
		houseApi.getHouseRoom(id).then(({data}: {data: HouseDetail}) => {
			// console.log('房源详情==============>', toRaw(data))

			if (data.houseBook && data.houseBook.bookStatus === 1) {
				disables.save = true
				XEUtils.assign(entity, defaultRenterContract())

				return Modal.warning({
					centered: true,
					title: '系统提示',
					content: '当前房源存在预定未支付记录，请先完成支付或作废后再进行签约'
				})
			} else {
				disables.save = false
			}

			entity.price = data.actualPrice
			entity.basePrice = data.basePrice
			entity.housePid = data.housePid
			entity.houseAddress = data.fullAddress
			entity.maintainerId = data.stewardId
			// getTemplates(data.deptId as string)
		})
	}

	const reset = () => {
		XEUtils.assign(entity, defaultRenterContract(), {
			contractId: null,
			contractNo: null,
			signEmpId: store.currentUser.empId,
			signDeptId: store.currentUser.deptId,
			signTime: nowDate(),
			// 包租合同自定义
			enterPriseId: null,
			enterPriseTeamWorkId: null,
			enterPriseTeamworkDiscountId: null,
			societyCode: null,
			linkmanPhone: null,
			enterPriseContractHouseRoomFroms: [],
			leasePeriod: 6,
			endTime: dayjs().add(6, 'month').add(-1, 'day').format(DATE_FORMAT.DATE),
			costPaymentConfigs: []
		})
	}

	const options = reactive<any>({
		// 客户来源
		sources: [],
		// 爱好
		hobbies: [],
		// 重点人群
		keyGroups: [],
		// 费用科目
		feeSubjects: [],
		// 证件类型
		certificateTypes: Object.keys(CERTIFICATION_TYPE_MAP).map(key => ({
			label: CERTIFICATION_TYPE_MAP[key],
			value: Number(key)
		})),
		// 企业列表
		enterpriseList: [],
		// 周期
		teamWork: [],
		// 折扣 协议
		discount: []
	})

	// 获取字典
	const getDisc = () => {
		settingApi.getDicListByPid(DIC_PID_MAP['CUSTOMER@HOBBY']).then(({data}) => (options.hobbies = data))
		settingApi.getDicListByPid(DIC_PID_MAP['CUSTOMER@KEY_GROUPS']).then(({data}) => (options.keyGroups = data))
		settingApi.getDicListByPid(DIC_PID_MAP['CUSTOMER@CHANNELSOURCE']).then(({data}) => (options.sources = data))
		settingApi.getDicListByLabel(DIC_LABEL_MAP['FEESUBJECT']).then(({data}) => (options.feeSubjects = data))

		// getEnterPriseLibraryListAll({}).then(({data}) => {
		// 	options.enterpriseList = data
		if (props.id) {
			contractDetails()
		}
		// })
	}

	// 选择企业
	const selectEnterPriseId = (value: any) => {
		let arr = options.enterpriseList.filter(e => e.id === value)[0]
		XEUtils.assign(enterPrise, arr)
		// 回显各个字段
		entity.societyCode = enterPrise.societyCode
		entity.linkmanName = enterPrise.linkmanName
		entity.linkmanPhone = enterPrise.linkmanPhone
		entity.renterInfo.name = enterPrise.linkmanName
		entity.renterInfo.phone = enterPrise.linkmanPhone
		entity.renterInfo.identityCard = enterPrise.linkmanIdCard
		entity.renterInfo.employer = enterPrise.enterPriseName

		options.teamWork = enterPrise.teamworks?.map((e: any) => {
			return {
				...e,
				period: e.beginTime.substr(0, 10) + '至' + e.endTime.substr(0, 10)
			}
		})

		// options回显name重构
		options.discount = enterPrise.teamworks?.map((i: any) => {
			let from = i.discounts?.map((e: any) => {
				let name =
					e.enterPriseTeamWordDetailsName +
					'/' +
					(e.type === 1 ? '折扣' : '') +
					'/' +
					discountTypeOptions.filter(j => j.value === e.discountType)[0]?.label +
					'/' +
					e.discountScale +
					'%'
				return {
					...e,
					name: name
				}
			})

			return {
				...i,
				discounts: from
			}
		})
		// 过滤出最优折扣id所在数组
		options.discount = options.discount?.filter((e: any) => {
			return e.discounts?.some((j: any) => j.id === enterPrise.enterPriseTeamWorkDicCountId)
		})[0].discounts

		// 折扣id和周期id 最优在最外层
		entity.enterPriseTeamWorkId = enterPrise.enterPriseTeamWorkId
		entity.enterPriseTeamworkDiscountId = enterPrise.enterPriseTeamWorkDicCountId

		discountScale.value = enterPrise.discountScale
		discountType.value = enterPrise.discountType
		checkData()
	}

	const selectWorkId = (value: any) => {
		let arr = enterPrise.teamworks.filter(e => e.id === value)[0]
		options.discount = arr?.discounts?.map((e: any) => {
			return {
				...e,
				name: e.enterPriseTeamWordDetailsName + '/' + e.discountScale + '%'
			}
		})
		entity.enterPriseTeamworkDiscountId = options.discount[0]?.id
		// 折扣默认选择第一个
		discountScale.value = options.discount[0]?.discountScale
		discountType.value = options.discount[0]?.discountType

		onSubmitSuccess()
		checkData()
	}

	const selectDiscountId = (value: any) => {
		options.teamWork.forEach((e: any) => {
			e.discounts.forEach(j => {
				if (j.id === value) {
					discountScale.value = j.discountScale
					discountType.value = j.discountType
				}
			})
		})

		onSubmitSuccess()
	}

	/**
	 * 合作周期是否和合同周期冲突
	 */
	const checkData = () => {
		let beginTime = options.teamWork?.filter((e: any) => e.id === entity.enterPriseTeamWorkId)[0]?.beginTime
		let endTime = options.teamWork?.filter((e: any) => e.id === entity.enterPriseTeamWorkId)[0]?.endTime
		if (
			(entity.beginTime as string) < beginTime ||
			(entity.beginTime as string) > endTime ||
			(entity.endTime as string) < beginTime ||
			(entity.endTime as string) > endTime
		) {
			entity.beginTime = null
			entity.endTime = null
			entity.leasePeriod = null
		}
	}

	const onClickToSelectHouse = () => {
		// 如果存在已选择房间 过滤id回显已选择房间
		if (entity.enterPriseContractHouseRoomFroms?.length) {
			houseInfoId.value = entity.enterPriseContractHouseRoomFroms.map(e => e.id)
		}
		visibles.selectHouse = true
	}

	const onClickToCostConfig = () => {
		visibles.costConfig = true
	}

	// 房间
	const houseInfoTable = ref<VxeTableInstance>()
	const houseTableOption = reactive<VxeTableProps>({
		size: 'small',
		maxHeight: 200,
		border: true,
		rowClassName: 'edit-table-row'
	})

	// 其它费用
	const otherBillTable = ref<VxeTableInstance>()
	const otherBillTableOption = reactive<VxeTableProps>({
		size: 'mini',
		maxHeight: 200,
		border: true,
		cellStyle: {padding: 0},
		rowClassName: 'edit-table-row'
	})

	// 添加其它费用
	const onClickToAddOtherBill = () => {
		entity.otherExpenses?.push({})

		otherBillTable.value?.reloadData(entity.otherExpenses as [])
	}

	const onClickToRemoveRow = (index: any, tableInstance: VxeTableInstance) => {
		Modal.confirm({
			title: '系统提示',
			content: '删除后无法恢复，确定删除？',
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			onOk() {
				tableInstance.data?.splice(index, 1)
				tableInstance.reloadData(tableInstance.data as [])
			}
		})
	}

	const onDateChange = (dates: string[]) => {
		dates = dates || []
		entity.beginTime = dates[0]

		if (options.teamWork.length) {
			if (dayjs(options.teamWork[0].period.slice(11, 21)).format(DATE_FORMAT.DATE) > dates[1]) {
				entity.endTime = dates[1]
			} else {
				entity.endTime = dayjs(options.teamWork[0].period.slice(11, 21)).format(DATE_FORMAT.DATE)
				message.warn('结束日期不能超过合同结束日期')
			}
		}
	}

	const quickSelectDate = () => {
		entity.beginTime = entity.beginTime || nowDate()

		let endTime = dayjs(entity.beginTime)
			.add(entity.leasePeriod || 6, 'month')
			.add(-1, 'day')
			.format(DATE_FORMAT.DATE)

		// 判断结束日期是否在周期内
		let begin = options.teamWork?.filter((e: any) => e.id === entity.enterPriseTeamWorkId)[0]?.beginTime
		let end = options.teamWork?.filter((e: any) => e.id === entity.enterPriseTeamWorkId)[0]?.endTime
		if (endTime >= begin && endTime <= end) {
			entity.endTime = endTime
		} else {
			entity.leasePeriod = null
			message.warn('结束日期不在合作周期内！')
		}
	}

	// 提交合同信息预览账单
	const submit = () => {
		form.value
			?.validate()
			.then(() => {
				if (!entity.enterPriseContractHouseRoomFroms?.length) {
					message.warn('请选择房间')
					return
				}
				if (!entity.costPaymentConfigs?.length) {
					message.warn('请完善费用支付配置')
					return
				}

				visibles.billPreview = true
			})
			.catch(({errorFields}: any) => {
				form.value?.scrollToField(errorFields[0].name, {
					behavior: 'smooth'
				})
			})
	}

	// 选择房间回显 and 周期 折扣 租金 押金
	const onSubmitSuccess = (data?: any) => {
		if (data) {
			newEletedTotal.value = data.length
			if (originalTotal.value) {
				entity.enterPriseContractHouseRoomFroms = [...data, ...originalList.value]
			} else {
				entity.enterPriseContractHouseRoomFroms = data
			}
		}

		entity.price = 0
		entity.deposit = 0
		entity.enterPriseContractHouseRoomFroms?.forEach((e: any) => {
			// 新增一个计算价格 后面账单预览使用
			e.countPprice = discountType.value === 1 ? Number(((e.price * Number(discountScale.value)) / 100).toFixed(2)) : e.price
			e.countDeposit = discountType.value === 1 ? Number(((e.deposit * Number(discountScale.value)) / 100).toFixed(2)) : e.deposit

			entity.price += e.countPprice
			entity.deposit += e.countDeposit
		})

		entity.price = Number(entity.price.toFixed(2))
		entity.deposit = Number(entity.deposit.toFixed(2))
	}

	const onSubmitCost = (data: any) => {
		entity.costPaymentConfigs = data
	}

	const onSubmitBill = (data: any) => {
		// 成功关闭弹窗
		option.onCancel()
	}

	// 监听 员工id 维护人和签约人合并
	watchEffect(() => {
		if (entity.signEmpId) {
			entity.maintainerId = entity.signEmpId
		}
	})

	const contractDetails = () => {
		getEnterContractDetails(props.id as string).then(({data}: any) => {
			console.log(data.enterPriseDTO, data)
			// 企业信息相关
			entity.enterPriseTeamWorkId = data.enterPriseTeamworkId
			entity.enterPriseTeamworkDiscountId = data.enterPriseTeamworkDiscountId
			// 企业信息相关
			options.enterpriseList.push({
				id: data.enterPriseDTO.id,
				enterPriseName: data.enterPriseDTO.enterPriseName
			})
			entity.enterPriseId = data.enterPriseDTO.id
			entity.societyCode = data.enterPriseDTO.societyCode
			entity.linkmanName = data.enterPriseDTO.linkmanName
			entity.linkmanPhone = data.enterPriseDTO.linkmanPhone
			// entity.renterInfo.identityCard = res.linkmanIdCard
			entity.renterInfo.employer = data.enterPriseDTO.enterPriseName

			options.teamWork.push({
				id: data.enterPriseTeamworkId,
				period: data.enterPriseDTO?.beginTime + '至' + data.enterPriseDTO?.endTime
			})

			teamWork.value.beginTime = data.enterPriseDTO.beginTime
			let name =
				data.enterPriseDTO.enterPriseTeamWordDetailsName +
				'/' +
				(data.enterPriseDTO.type === 1 ? '折扣' : '') +
				'/' +
				data.enterPriseDTO.discountType +
				'/' +
				data.enterPriseDTO.discountScale +
				'%'
			options.discount.push({
				id: data.enterPriseTeamworkDiscountId,
				name
			})

			discountScale.value = data.enterPriseDTO.discountScale
			discountType.value = data.enterPriseDTO.discountType
			//承租人相关
			entity.renterInfo = data.renterInfoDTO
			entity.renterInfo.interest = data.renterInfoDTO.interest || []
			entity.renterInfo.gender = data.enterPriseDTO.gender
			entity.renterInfo.employer = data.renterInfoDTO.workAddres

			//房间信息相关
			entity.enterPriseContractHouseRoomFroms = data.houseRoomDTOList.map((e: any) => {
				return {
					id: e.id,
					houseId: e.id,
					housePid: e.id,
					houseAddress: e.fullBaseAddress,
					price: e.actualPrice,
					countPprice: e.actualPrice * (data.enterPriseDTO.discountScale / 100),
					countDeposit: e.deposit,
					houseArea: e.houseArea + '平',
					houseRoomTypeName: e.roomTypeName,
					currentFloor: e.currentFloor + '/' + e.totalFloor,
					isShowStatus: true
				}
			})
			originalList.value = XEUtils.clone(entity.enterPriseContractHouseRoomFroms, true)
			originalTotal.value = data.houseRoomDTOList.length || 0
			// entity.renterInfo = data.renterInfoDTO
			entity.renterInfo.interest = data.renterInfoDTO.interest || []

			//合同相关
			entity.signType = data.signType
			entity.contractNo = data.contractNo
			// entity.beginTime = data.beginTime
			// entity.endTime = data.endTime
			entity.deposit = data.deposit
			entity.price = data.price
			entity.periodMonth = data.periodMonth
			entity.depositMonth = data.depositMonth
			entity.payPatternValue = data.payPattern
			// entity.cycleType = data.cycleType
			entity.signTime = data.signTime
			entity.addExplanation = data.addExplanation
		})
	}
</script>

<style lang="less">
	.add-charter {
		.ant-modal-body {
			padding: 0 16px;
			overflow: auto;
			min-height: 600px;
			max-height: 1000px;
			height: calc(100vh - 200px);

			.ant-form-item {
				margin-bottom: 16px;

				label[for='form_item_beginTime'] {
					display: flex;

					.display-flex {
						flex: 1;
						justify-content: space-around;
					}
				}
			}

			.custom-radio-group {
				.ant-space {
					display: flex;

					.ant-space-item {
						flex: 1;
					}
				}

				.ant-radio-button-wrapper {
					height: 96px;
					display: block;

					.ant-typography {
						margin-bottom: 6px;
					}
				}
			}

			.template-select-wrapper {
				.ant-form-item-control {
					flex-direction: row;
					align-items: center;
					gap: 16px;

					.ant-select-selection-search {
						left: 0;
					}

					.ant-form-item-extra {
						color: @warning-color;
						font-size: @font-size-sm;
					}
				}

				.ant-select {
					width: 160px;

					.ant-select-selector {
						padding: 0;
						font-size: @font-size-sm;
					}
				}
			}

			.month-quick-radio-group {
				.ant-radio-button-wrapper {
					padding: 0 9px;
				}
			}

			.ant-input-number-group-addon {
				background: #fff;
				color: @text-color;
			}

			.edit-table-row {
				.ant-input,
				.ant-select-selector {
					padding: 0;
					border: none;
				}

				.ant-select,
				.ant-input-number {
					width: 100%;
				}

				.ant-radio-wrapper:last-child {
					margin-right: 0;
				}
			}
		}
	}
</style>
